package 剑指offer;

import org.junit.Test;

public class 把字符串转换为整数 {

    public int strToInt(String str) {
        if (str==null || str.equals(""))
            return 0;
        long res=0;
        int i=0;
        boolean b=true;
        char[] chars = str.toCharArray();
        while (chars[i]==' '){
            i++;
            if (i==chars.length)
                return 0;
        }
        //不满足条件，直接返回0
        if (!Character.isDigit(chars[i]) && chars[i]!='-' && chars[i]!='+')
            return 0;
        if (chars[i]=='+'){
            i++;
        }
        else if (chars[i]=='-'){
            i++;
            b=false;
        }
        if (i==chars.length)
            return 0;
        while (Character.isDigit(chars[i])){
            res=res*10+chars[i]-'0';
            //判断是否越界
            if (b==true && res>Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (b==false && -res<Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
            i++;
            if (i==chars.length)
                break;
        }
        return b?(int)res:(int)-res;
    }

    @Test
    public void test(){
        String s=" ";
        char[] chars = s.toCharArray();

    }
}
